<template>
  <layout :showBg="false">
    <template #header>
      <pageHead title="用户信息" />
    </template>
    <view class="content">
      <view class="flex flex-c flex-a-c">
        <image
          @click="choosePic"
          class="avatar"
          :src="avatar || require('../../../assets/images/logo.png')"
        ></image>

        <text class="c-60 fs-24">点击头像修改</text>
      </view>
      <view class="flex flex-a flex-bt">
        <view class="flex flex-a">
          <view>昵称</view>
          <input
            v-model="nickName"
            placeholder=""
            :disabled="disabled"
            :focus="focus"
            placeholder-class="input-placeholder"
          />
        </view>
        <view class="flex">
          <view @click="saveName">{{ disabled ? "修改" : "保存" }}</view>
        </view>
      </view>
    </view>
  </layout>
</template>
<script>
import layout from "../../../compennts/layout/index.vue";
import pageHead from "../../../compennts/pageHead/index.vue";
import { getLocalUserInfo } from "../../../assets/utils/index";
import { updateProfile } from "../../../api/setting/index";
import { getHsyToken } from "../../../api/plugins/index";
import { formatDate } from "../../../assets/utils/date";
import { randomString } from "../../../assets/utils/index";
import {
  pathToBase64,
  base64ToPath,
} from "../../../js_sdk/mmmm-image-tools/index";
import "../../../assets/utils/tos.min.js";
export default {
  components: {
    layout,
    pageHead,
  },
  data() {
    return {
      avatar: "",
      nickName: "",
      disabled: true,
      focus: false,
      client: null,
    };
  },
  onShow() {
    this.avatar = getLocalUserInfo().avatar;
    this.nickName = getLocalUserInfo().nickName;
  },
  methods: {
    async initTOS() {
      return new Promise(async (resolve, reject) => {
        const { data } = await getHsyToken();
        console.log("额额呃呃呃：", data);
        const { AccessKeyId, SessionToken, SecretAccessKey } =
          data.Result.Credentials;
        this.client = new TOS({
          accessKeyId: AccessKeyId, // 临时密钥的 Access Key
          accessKeySecret: SecretAccessKey, // 临时密钥的 Secret Key
          stsToken: SessionToken, //从 STS 服务获取的安全令牌
          region: "cn-beijing", // 所在地域
          bucket: "cps-oss-public", //Bucket 名称。
        });
        resolve();
      });
    },
    choosePic() {
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album"],//, "camera"],
        success: async (res) => {
          this.handleUpload(res);
        },
        fail: (res) => {
          console.log(res);
          this.$u.toast("出错啦~");
        },
      });
    },
    getFileByPath(path) {
      return new Promise((resolve, reject) => {
        pathToBase64(path)
          .then((base64) => {
            resolve(base64);
          })
          .catch((error) => {
            console.error(error);
          });
      });

      // uni.
    },
    async handleUpload(res) {
      console.log("选择的图片", res);
      let file = res.tempFiles[0];
      let fileName = file.path.split("/").pop();
      console.log(fileName);
      let date = formatDate(new Date()).split(" ")[0];
      await this.initTOS();
      let key = `mediumapp/${date}/${randomString(5)}_${fileName}.png`;
      // let base64File = await this.getFileByPath(file.path);
      // console.log('bas64:',base64File)
      // this.avatar = base64File;
      // uni.uploadFile({
      //           url: 'https://cps-oss-public.tos-cn-beijing.volces.com/mediumapp', // 这里填写你的文件上传URL
      //           filePath: file.path,
      //           name: 'file', // 服务器端通过这个字段接收文件
      //           formData: {
      //               'user': '某人'
      //           },
      //           success: (uploadRes) => {
      //               // 上传成功后的处理
      //               console.log(uploadRes);
      //           }
      //       });
      // const buffer = uni.base64ToArrayBuffer(base64File);
      // console.log('buffer:',buffer)
      const result = await this.client.uploadFile({
        key: key,
        file: file,
      });
      // let src = `https://cps-oss-public.tos-cn-beijing.volces.com/${key}`;
      console.log("上傳結果：", result);
      this.onUploadAvatart(result.data.Location);
    },
    onUploadAvatart(avatar) {
      updateProfile({
        nickName: this.nickName,
        avatar,
      }).then((res) => {
        this.$u.toast("修改成功");
        this.avatar = avatar;
        this.disabled = true;
        this.focus = false;
      });
    },
    saveName() {
      if (this.disabled) {
        this.disabled = false;
        this.focus = true;
        return;
      }
      updateProfile({
        nickName: this.nickName,
        avatar: this.avatar,
      }).then((res) => {
        this.$u.toast("修改成功");
        this.disabled = true;
        this.focus = true;
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../../assets/styles/common.less");
.content {
  min-height: 100%;
  background: #f7f8ff;
  padding: 32rpx;
  .avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    margin: 50rpx auto;
  }
}
</style>
